<template>
  <div class="cart-container">
    <h2 class="cart-title">我的购物车</h2>
    <div class="cart-items" v-if="cartItems.length">
      <div class="cart-item" v-for="item in cartItems" :key="item.id">
        <div class="item-left">
          <img v-lazy="item.photo" alt="" />
          <div class="item-info">
            <div class="item-name">{{ item.name }}</div>
            <div class="item-desc">{{ item.description }}</div>
            <div class="item-price">¥ {{ item.price }}</div>
          </div>
        </div>
        <div class="item-right">
          <el-button type="danger" size="small" plain @click="removeFromCart(item.id)">
            <el-icon><Delete /></el-icon>
            移除
          </el-button>
        </div>
      </div>
    </div>
    <div v-else class="empty-cart">
      <el-empty description="购物车是空的">
        <el-button type="primary">去购物</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getCartList, removeFromCart } from '@/api/index.js'
import { ElMessage } from 'element-plus'

const cartItems = ref([])

const fetchCartItems = async () => {
  const userId = localStorage.getItem('userInfo').id
  
  try {
    const res = await getCartList(userId)
    cartItems.value = res.data
  } catch (error) {
    ElMessage.error('获取购物车数据失败')
  }
}

const removeItem = async (id) => {
  try {
    await removeFromCart(id)
    await fetchCartItems()
    ElMessage.success('成功移除商品')
  } catch (error) {
    ElMessage.error('移除商品失败')
  }
}

onMounted(() => {
  fetchCartItems()
})
</script>

<style scoped>
.cart-container {
  padding: 20px;
}

.cart-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.item-photo {
  width: 100px;
  height: 75px;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
  margin-left: 20px;
}

.item-name {
  font-size: 16px;
  font-weight: 500;
}

.item-price {
  color: #e74c3c;
  margin-top: 8px;
}

.empty-cart {
  text-align: center;
  padding: 40px;
  color: #666;
}
</style> 